package cn.south.campus.business.service.impl;

import cn.south.campus.business.mapper.ExpressApplyMapper;
import cn.south.campus.business.model.entity.ExpressApply;
import cn.south.campus.business.model.enums.ExpressTakeEnums;
import cn.south.campus.business.model.vo.ExpressApplyVo;
import cn.south.campus.business.service.ExpressApplyService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 快递代取申请 服务实现类
 * </p>
 *
 * @author chow
 * @since 2024-12-13
 */
@Service
@AllArgsConstructor
public class ExpressApplyServiceImpl extends ServiceImpl<ExpressApplyMapper, ExpressApply> implements ExpressApplyService {

    private final ExpressApplyMapper expressApplyMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rejectTakeApply(Long takeId, Long notApplyId) {
        LambdaUpdateWrapper<ExpressApply> wrapper = new LambdaUpdateWrapper<ExpressApply>()
                .set(ExpressApply::getStatus, ExpressTakeEnums.TakeApplyStatus.REFUSE.getCode())
                .eq(ExpressApply::getExpressTakeId, takeId)
                .ne(notApplyId != null, ExpressApply::getId, notApplyId);
        expressApplyMapper.update(null, wrapper);
    }

    @Override
    public List<ExpressApplyVo> applyRecord(Long takeId, Long userId, String keyword) {
        List<ExpressApply> applyList = expressApplyMapper.selectRecord(takeId, userId, keyword);
        if (CollectionUtils.isEmpty(applyList)) {
            return null;
        }
        return applyList.stream().map(ExpressApplyVo::convert).collect(Collectors.toList());
    }

    @Override
    public Integer applyStatus(Long takeId, Long userId) {
        LambdaQueryWrapper<ExpressApply> wrapper = new LambdaQueryWrapper<ExpressApply>()
                .eq(ExpressApply::getExpressTakeId, takeId)
                .eq(ExpressApply::getUserId, userId);
        ExpressApply expressApply = expressApplyMapper.selectOne(wrapper);
        if (expressApply == null) {
            return ExpressTakeEnums.TakeApplyStatus.NO.getCode();
        }
        return expressApply.getStatus();
    }

    @Override
    public ExpressApply queryAcceptRecord(Long takeId) {
        LambdaQueryWrapper<ExpressApply> wrapper = new LambdaQueryWrapper<ExpressApply>().eq(ExpressApply::getExpressTakeId, takeId)
                .eq(ExpressApply::getStatus, ExpressTakeEnums.TakeApplyStatus.PASS.getCode());
        return expressApplyMapper.selectOne(wrapper);
    }
}
